import { Button, ConfigProvider, Drawer } from "antd";
import { useState, useRef, useEffect } from "react";

const withForm = (FormCmp) => {

  const CmpWithForm = ({ initialValues = {}, visible = true, title, width = "35%", okText, okTrigger, cancelTrigger, afterClose }) => {
    const [isOpen, setIsOpen] = useState(visible);
    const formRef = useRef(null);

    // 确定按钮点击
    const okHandler = () => {
      const fromIns = formRef.current.form;
      fromIns.validateFields().then(values => {
        //console.log("校验通过 values = ", values);
        okTrigger(values, closeTrigger);
      }).catch(error => {
        //console.log("表单校验不通过!");
      })
    }

    /**
     * 关闭
     */
    const closeTrigger = () => {
      setIsOpen(false);
    }

    // 取消按钮点击
    const cancelHandler = () => {
      setIsOpen(false);
      if (cancelTrigger) {
        cancelTrigger();
      }
    }

    useEffect(() => {
      if (!isOpen) {
        // 关闭后销毁dom
        afterClose();
      }
    }, [isOpen])

    return (
      <ConfigProvider theme={{
        token: {
          borderRadius: 2,
        }
      }}>
        <Drawer
          title={title}
          width={width}
          open={isOpen}
          onClose={() => setIsOpen(false)}
          maskClosable={false}
          footer={<Footer okText={okText} okTrigger={okHandler} cancelTrigger={cancelHandler} />}
        >
          <div style={{}}>
            <FormCmp ref={formRef} initialValues={initialValues} />
          </div>
        </Drawer>
      </ConfigProvider>
    )
  }

  return CmpWithForm;

}

/**
 * 底部按钮组件
 * @param {*} param0 
 * @returns 
 */
const Footer = ({ okText = '确定', cancelText = '取消', okTrigger, cancelTrigger }) => {

  return (
    <div style={{ height: '40px', marginTop: '6px', display: 'flex', flexDirection: 'row-reverse' }}>
      <Button onClick={() => { cancelTrigger() }}>
        {cancelText}
      </Button>
      <Button type="primary" style={{ marginRight: '10px' }} onClick={() => okTrigger()}>
        {okText}
      </Button>
    </div>
  )
}

export default withForm;